import React, { Component,createContext } from 'react'
import './index.css'

const MyContext = createContext()
const { Provider,Consumer } = MyContext

export default class Demo5 extends Component {
  render() {
    return (
      <div>
        <A></A>
      </div>
    )
  }
}

class A extends Component {
  state={username:'joker',age:23}
  render() {
    const { username,age } = this.state
    return (
      <div className="parent">
        <h2>我是A组件</h2>
        <h3>我要传的数据是：{username+age}</h3>
        <Provider value={{username,age}}>
          <B/>
        </Provider>
      </div>
    )
  }
}

class B extends Component {
  render() {
    return (
      <div className="child">
        <h2>我是B组件</h2>
        <h3>我从A组件接收到的数据是：{'???'}</h3>
        <C/>
      </div>
    )
  }
}

class C extends Component {
  render() {
    return (
      <div className="grandson">
        <h2>我是C组件</h2>
        <h3>我从A组件接收到的数据是：{'???'}</h3>
        <D/>
      </div>
    )
  }
}

class D extends Component {
  render() {
    return (
      <div className="grandson1">
        <h2>我是D组件</h2>
        <h3>我从A组件接收到的数据是：{'???'}</h3>
        <E/>
        <F/>
      </div>
    )
  }
}

class E extends Component {
  //声明接收context
  static contextType=MyContext
  render() {
    const { username,age } = this.context
    return (
      <div className="grandson2">
        <h2>我是E组件</h2>
        <h3>我从A组件接收到的数据是：{`${username}今年${age}岁`}</h3>
      </div>
    )
  }
}

function F (){
  return (
    <div className="grandson2">
        <h2>我是F组件,函数组件</h2>
        <h3>我从A组件接收到的数据是：{
          <Consumer>
            {
              value =>`${value.username}今年${value.age}岁`
            }
          </Consumer>
        }</h3>
      </div>
  )
}
